<template>
    <u-popup
        v-model="showPopup"
        mode="center"
        border-radius="20"
        width="90%"
        height="80%"
        closeable="true"
        :mask-close-able="false"
        @close="cancelGift(false)"
    >
        <view class="gift-selection-container">
            <u-toast ref="uToast" />
            <view class="gift-title">
                分配商品比列（总比例100
                <view>
                    ,已分配
                    <text class="num">{{
                        numRatio > 100 ? "100+" : numRatio
                    }}</text>
                </view>
                ）
            </view>
            <!-- 赠品列表 -->
            <scroll-view
                class="gift-list"
                scroll-y="true"
                enable-back-to-top="true"
            >
                <black v-for="(item, index) in list" v-if="list.length > 0">
                    <view
                        class="gift-item"
                        :key="index"
                        v-if="
                            (item.busType == '0' || item.busType == '1') &&
                            item.isRatio
                        "
                    >
                        <view class="product-info-row flex align-center">
                            <!-- 商品图片 -->
                            <view class="product-image-wrapper">
                                <image
                                    class="product-image"
                                    :src="getImageUrl(item)"
                                    mode="aspectFill"
                                    @error="onImageError"
                                />
                            </view>

                            <!-- 商品信息 -->
                            <view class="product-info">
                                <view class="product-name">
                                    <template v-if="item.busType == '0'">
                                        {{
                                            item.shopInv.basInv.cinvname
                                        }}</template
                                    >
                                    <template v-if="item.busType == '1'">
                                        {{
                                            item.shopProductSell.basInv.cinvname
                                        }}</template
                                    >
                                </view>
                                <view
                                    style="display: flex; align-items: center"
                                >
                                    比例：
                                    <u-input
                                        v-model="item.ratio"
                                        type="number"
                                        height="50rpx"
                                        style="width: 240rpx;"
                                        :border="true"
                                        @focus="focus(item.ratio, item)"
                                        @blur="blur($event, item)"
                                    />
                                    <!-- <u-number-box
                                        positive-integer
                                        v-model="item.ratio"
                                        :min="0"
                                        :max="100"
                                        input-width="150"
                                        input-height="50"
                                        @blur="blur($event, item, index)"
                                    /> -->
                                </view>
                            </view>
                        </view>
                    </view>
                    <black v-if="item.busType == '3'">
                        <black v-for="(it, index1) in item.salesRefList">
                            <view
                                class="gift-item"
                                :key="index1"
                                v-if="it.isRatio"
                            >
                                <view
                                    class="product-info-row flex align-center"
                                >
                                    <!-- 商品图片 -->
                                    <view class="product-image-wrapper">
                                        <image
                                            class="product-image"
                                            :src="getImageUrl(it)"
                                            mode="aspectFill"
                                            @error="onImageError"
                                        />
                                    </view>

                                    <!-- 商品信息 -->
                                    <view class="product-info">
                                        <view class="product-name">
                                            <template>
                                                {{
                                                    it.basInv.cinvname
                                                }}</template
                                            >
                                        </view>
                                        <view style="display: flex; align-items: center">
                                            比例：
                                            <u-input
                                                v-model="it.ratio"
                                                type="number"
                                                height="50rpx"
                                                style="width: 240rpx"
                                                :border="true"
                                                @focus="
                                                    focus(it.ratio, item, it)
                                                "
                                                @blur="blur($event, item, it)"
                                            />
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </black>
                    </black>
                </black>
            </scroll-view>

            <!-- 底部按钮 -->
            <view class="bottom-buttons">
                <view class="button cancel-btn" @click="cancelGift(true)">
                    取消
                </view>
                <view class="button confirm-btn" @click="confirmGift">
                    确定比列
                </view>
            </view>

            <!-- 错误提示弹窗 -->
            <u-modal
                v-model="showErrorModal"
                :show-cancel-button="false"
                confirm-text="确定"
                @confirm="showErrorModal = false"
            >
                <view class="error-modal-content">
                    <view class="error-icon">✕</view>
                    <view class="error-title"
                        >所带赠品金额超过本次使用账户余额</view
                    >
                    <view class="error-subtitle">无法再继续添加赠品</view>
                </view>
            </u-modal>
        </view>
    </u-popup>
</template>

<script>
import { mapState } from "vuex";

export default {
    name: "GiftSelection",
    props: {
        show: {
            type: Boolean,
            default: false,
        },
        findInvExcDataList: {
            type: Array,
            default: [],
        },
    },
    computed: {
        ...mapState(["vuex_config", "vuex_basCus"]),
        // 代理 show prop，避免直接修改 prop
        showPopup: {
            get() {
                return this.show;
            },
            set(value) {
                this.$emit("update:show", value);
            },
        },
        // list() {
        //     return this.findInvExcDataList;
        // },
        numRatio() {
            return this.list.reduce((sum, item) => {
                if (item.busType == "0" || item.busType == "1") {
                    sum += Number(item.ratio || 0);
                }
                if (item.busType == "3") {
                    item.salesRefList.forEach((it) => {
                        sum += Number(it.ratio || 0);
                    });
                }
                return sum;
            }, 0);
        },
    },
    data() {
        return {
            // giftList: [],
            baseUrl: "",
            showErrorModal: false,
            list: [],
        };
    },
    watch: {
        show: {
            handler(newVal) {
                if (newVal) {
                    this.list = [...this.findInvExcDataList];
                }
            },
            immediate: true,
        },
    },
    mounted() {
        this.baseUrl = this.vuex_config ? this.vuex_config.baseUrl : "";
    },
    methods: {
        // 获取图片URL
        getImageUrl(item) {
            if (item.busType == "0") {
                return item.shopInv.basInv.picUrl
                    ? this.baseUrl + item.shopInv.basInv.picUrl
                    : "";
            }
            if (item.busType == "1") {
                return item.shopProductSell.picUrl
                    ? vuex_config.baseUrl + item.shopProductSell.picUrl
                    : "";
            }
            // item = item.shopInv;
            // if (item.basInv && item.basInv.picUrl) {
            //     if (item.basInv.picUrl.startsWith("http")) {
            //         return item.basInv.picUrl;
            //     }
            //     return this.baseUrl + item.basInv.picUrl;
            // }
            // return "/static/image/commodity.png";
        },

        // 图片加载失败
        onImageError() {
            console.log("图片加载失败");
        },

        // 取消赠品
        cancelGift(Boolean) {
            this.$emit("cancel", Boolean);
        },

        // 确定带赠品
        confirmGift() {
            if (100 < this.numRatio) {
                return uni.showToast({
                    title: "分配比例不能大于100",
                    icon: "none",
                });
            }
            this.$emit("confirm", this.list, this.numRatio);
            this.cancelGift(false);
            this.list = [];
        },
        focus(e, item, it) {
           
            if (!Number(e)) {
                if (item.busType == "0" || item.busType == "1") {
                    item.ratio = undefined;
                } else {
                    it.ratio = undefined;
                }
            }
        },
        blur(e, item, it) {
            if (isNaN(Number(e)) || Number(e) < 0 || Number(e) > 100) {
                if (item.busType == "0" || item.busType == "1") {
                    item.ratio = 0;
                } else {
                    it.ratio = 0;
                }
            } else {
                if (item.busType == "0" || item.busType == "1") {
                    item.ratio = Number(e).toFixed(0);
                } else {
                    it.ratio = Number(e).toFixed(0);
                }
            }

            this.$forceUpdate();
        },
    },
};
</script>

<style lang="scss" scoped>
.gift-selection-container {
    background-color: #f5f5f5;
    height: 100%;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
}
.gift-title {
    display: flex;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    .num {
        color: #ff4757;
    }
}

.gift-list {
    flex: 1;
    overflow-y: auto;

    .gift-item {
        background-color: #fff;
        border-radius: 20rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        flex-wrap: wrap; // 允许第一行独占显示
        position: relative;

        .product-image-wrapper {
            margin-right: 20rpx;

            .product-image {
                width: 120rpx;
                height: 120rpx;
                border-radius: 12rpx;
                background-color: #f5f5f5;
            }
        }

        .product-info {
            flex: 1;
            margin-right: 20rpx;

            .product-name {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
                margin-bottom: 10rpx;
                line-height: 1.4;
                width: 385rpx;
            }
        }
    }
}

.bottom-buttons {
    background-color: #fff;
    padding: 30rpx;
    display: flex;
    gap: 20rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
    margin-top: auto;

    .button {
        flex: 1;
        height: 88rpx;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: bold;

        &.cancel-btn {
            background-color: #f5f5f5;
            color: #666;
        }

        &.confirm-btn {
            background-color: #ff6b35;
            color: #fff;
        }
    }
}

.error-modal-content {
    text-align: center;
    padding: 40rpx;

    .error-icon {
        width: 80rpx;
        height: 80rpx;
        background-color: #ff4757;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        font-weight: bold;
        margin: 0 auto 30rpx;
    }

    .error-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
    }

    .error-subtitle {
        font-size: 28rpx;
        color: #666;
    }
}
.u-numberbox {
    .u-icon-minus,
    .u-icon-plus {
        display: none !important;
    }
}
/deep/ .u-input {
    .u-input__input {
        height: 50rpx !important;
    }
}
</style>
